<template>
  <div id="details">
    <el-row><br></el-row>
    <div class="main">
      <!-- 左侧商品轮播图 -->
      <el-row>
        <el-col :offset="1" :span="12" style="color: white;">
          <div class="block">
            <el-carousel style="height: 360px; width: 640px" v-if="game.media.length>1" indicator-position="outside"
                         :autoplay="false">
              <el-carousel-item v-for="item in game.media" :key="item">
                <div v-if="item.type == 0">
                  <el-image style="height:360px; width: 640px;" :src="item.src"/>
                </div>
                <div v-else>
                  <video-player class="video-player vjs-custom-skin"
                                ref="videoPlayer"
                                :playsinline="true"
                                :options="playerOptions">
                  </video-player>
                </div>
              </el-carousel-item>
            </el-carousel>
            <div v-else>
              <el-image
                  style="height:360px;"
                  :src="game.picture"
              />
            </div>
          </div>
        </el-col>
        <!-- 左侧商品轮播图END -->
        <!-- 右侧内容区 -->
        <el-col :offset="2" span="8" style="background-color: #343434; color: white; padding: 10px;">

          <el-row style="text-align: center;"><h1 class="name">{{ game.name }}</h1></el-row>
          <el-rate
              v-model="game.scores"
              disabled
              show-score
              text-color="#ff9900"
              style="text-align: center;">
          </el-rate>
          <el-row><p class="intro">{{ game.profile }}</p></el-row>
          <el-row>
            <el-col span="12" class="price" style="text-align: center;">
              <div v-if="game.discountPrice">
                <span>-{{ game.discount }}%</span>
                <span style="text-decoration: line-through;">￥{{ game.price }}元</span>
                <span>￥{{ game.discountPrice }}元</span>
                <br/>
                <span>折扣到期时间：{{ game.discountToTime }}</span>
              </div>
              <div v-else>
                <span>￥{{ game.price }}元</span>
              </div>
            </el-col>
            <el-col offset="4" span="8">
              <el-button :disabled="!game.isReleased" type="primary" round @click="do_operate(operate)">{{
                  operate
                }}
              </el-button>
            </el-col>
          </el-row>
          <!-- 右侧内容区END -->
        </el-col>
      </el-row>
    </div>

    <el-dialog v-if="game.isBought" :visible.sync="operate_show" title="下载">
      <span class="choose_edition">
        <el-select v-model="selected_edition" filterable placeholder="选择版本">
        <el-option
            v-for="edition in this.editions"
            :key="edition.edition"
            :label="edition.edition+' '+edition.gameEditionProfile+' '+edition.updateTime"
            :value="edition.source">
        </el-option>
      </el-select>
      </span>
      <span slot="footer" class="download_operate">
        <el-button type="primary" round @click="download">确认下载</el-button>
        <el-button type="info" @click="operate_show = false" round>取消</el-button>
      </span>
    </el-dialog>

    <el-dialog v-else :visible.sync="operate_show">
    <span class="balance">
      <el-button @click="payByBalance"><div class="el-icon-wallet">通过账户余额付款</div></el-button>

    </span>
      <span class="alipay">
      <el-button class="alipay" @click="payByAlipay">
        <el-image style="width: 18px;height: 18px" :src="require('@/assets/alipay.svg')"></el-image>
        通过支付宝付款
      </el-button>
    </span>
    </el-dialog>

    <div class="dlc" style="color: #000000;">
      <el-row v-for="dlc in game.dlc" v-bind:key="dlc" type="flex" style="margin-bottom: 20px;">
        <el-col style="background-color: #000000;">
          <el-card>
            <el-row>
              <el-col span="6">
                <el-image :src="dlc.img"
                          style="height: 90px; width: 160px;"></el-image>
              </el-col>
              <el-col span="2">
                <div class="dlcName">{{ dlc.name }}</div>
              </el-col>
              <el-col span="8">
                <div class="dlcIntro" style="word-break: break-all;">{{ dlc.intro }}</div>
              </el-col>
              <el-col span="6">
                <el-rate
                    v-model="dlc.score"
                    disabled
                    show-score
                    text-color="#ff9900"
                    score-template="{value}">
                </el-rate>
              </el-col>
              <el-col span="2">
                <el-button icon="el-icon-download" circle></el-button>
              </el-col>
            </el-row>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <comment-input v-bind:is-bought.sync="this.game.isBought" :game-id="this.game.id"></comment-input>
    <comments :comments="this.commentsData"></comments>

  </div>
</template>
<script>
// eslint-disable-next-line no-unused-vars
import {mapActions} from "vuex";
import {select_one_game, select_edition} from "@/api/game";
import {checkIsBought} from "@/api/user";
import {pay_by_balance, alipay} from "@/api/pay";
import commentInput from "@/components/commentInput";
import comments from "@/components/comments";
import baseUrl from "@/api/baseUrl";

export default {
  components: {commentInput, comments},
  data() {
    return {
      operate_show: false,
      operate: '',
      selected_edition: '',
      editions: [],
      game: {
        id: "",
        name: "test",
        media: [],
        intro: "testIntro",
        price: '10',
        isdiscount: true,
        discount: '90',
        price_after_discount: '1',
        discount_ddl: '2020-12-31',
        score: 5,
        isBought: false,
        dlc: [
          {
            img: require("@/assets/3.jpg"),
            name: "dlc",
            intro:
                "dlc of testhhhhh hhhhhhhhhh hhhhhhhhhhhhh hhhhhhhhhhhhhhh hhhhhhhhh hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhs",
            price: 123,
            isBought: false,
          },
          {
            img: require("@/assets/3.jpg"),
            name: "dlc",
            intro: "dlc of test",
            price: 123,
            isBought: false,
          },
          {
            img: require("@/assets/3.jpg"),
            name: "dlc",
            intro: "dlc of test",
            price: 123,
            isBought: false,
          },
        ],
      }, // 商品详细信息
      commentsData: [""],
      playerOptions: {
        playbackRates: [0.5, 1.0, 1.5, 2.0], // 可选的播放速度
        autoplay: false, // 如果为true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 是否视频一结束就重新开始。
        preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: 'zh-CN',
        aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [{
          type: "video/mp4", // 类型
          src: require('@/assets/game_vids/pix_sustech_vid.mp4'),// url地址
        }],
        poster: '', // 封面地址
        notSupportedMessage: '此视频暂无法播放，请稍后再试', // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true, // 当前时间和持续时间的分隔符
          durationDisplay: true, // 显示持续时间
          remainingTimeDisplay: false, // 是否显示剩余时间功能
          fullscreenToggle: true // 是否显示全屏按钮
        }
      }
    };
  },
  // 通过路由获取商品id
  mounted() {
    // console.log(this.$route.query);
    if (this.$route.query.id !== undefined) {
      this.game.id = this.$route.query.id;
      this.getInfo(this.game)
      // console.log(this.game.id);
    }
  },
  watch: {
    // 监听商品id的变化，请求后端获取商品数据
    // game: function (val) {
    //   this.getDetails(val);
    //   this.getPicture(val);
    // },
  },
  computed: {
    // operate: function () {
    //   if (!this.game.isReleased) {
    //     return "尚未发布"
    //   } else if (!this.game.isBought) {
    //     return "购买"
    //   } else if (this.game.isBought) {
    //     return "下载"
    //   } else {
    //     return "购买"
    //   }
    // }
  },
  methods: {
    getInfo(val) {
      let id = val.id;
      select_one_game(id).then((response) => {
        let code = response.data.code;
        // console.log(response.data)
        let gameDetail = response.data.data.gameDetail;
        let gameMedia = response.data.data.gameMedia;
        console.log(gameDetail);
        console.log(gameMedia);
        if (code == 200) {
          this.game = gameDetail;
          this.game.media = gameMedia;
          for (let i = 0; i < this.game.media.length; i++) {
            this.game.media[i].path = baseUrl + this.game.media[i].path.slice(1);
            this.game.media[i].src = this.game.media[i].path;
            let type = this.game.media[i].path.substr(-3);
            console.log(type)
            if (type == "png") {
              this.game.media[i].type = 0;
            }
            if (type == "jpg") {
              this.game.media[i].type = 0;
            }
            if (type == "mp4") {
              this.game.media[i].type = 1;
            }
          }
          console.log(this.game.media)
          checkIsBought(this.$store.getters.getToken, id).then(response => {
            let code = response.data.code;
            this.game.isBought = code == 200;
            // console.log(this.game)
            // console.log(this.game.isReleased)
            // console.log(this.game.isBought)
            if (!this.game.isReleased) {
              this.operate = "尚未发布"
            } else if (!this.game.isBought) {
              this.operate = "购买"
            } else if (this.game.isBought) {
              this.operate = "下载"
            } else {
              this.operate = "购买"
            }
          })
        }
      })
    }, do_operate(operate) {
      if (operate == '购买') {
        this.operate_show = true;
      } else if (operate == '下载') {
        select_edition(this.$store.getters.getToken, this.game.id, 1, 6).then(response => {
          let code = response.data.code;
          // console.log(response.data.data.records)
          if (code == 200) {
            this.editions = response.data.data.records;
            this.selected_edition = this.editions.length ? this.editions[0].source : '';
          } else {
            this.$alert('版本获取错误')
          }
        })
        this.operate_show = true;
      }
    },
    payByBalance() {
      pay_by_balance(this.$store.getters.getToken, this.game.id).then(response => {
        let code = response.data.code;
        if (code == 200) {
          this.operate_show = false;
          location.reload();
        } else if (code == 501) {
          this.$alert('您已经购买了该游戏')
          this.operate_show = false;
          location.reload();
        }
      })
    },
    payByAlipay() {
      alipay(this.$store.getters.getToken, this.game.id, this.game.name, 1, this.game.discountPrice ? this.game.discountPrice : this.game.price).then(response => {
        console.log(response)
        let status = response.status;
        if (status == 200) {
          const div = document.createElement('div')
          /* 此处form就是后台返回接收到的数据 */
          div.innerHTML = response.data
          document.body.appendChild(div)
          document.forms[0].submit()
        }

      })
    },
    download() {
      // download_game(this.$store.getters.getToken, this.selected_edition)
      const a = document.createElement('a');
      a.href = baseUrl + this.selected_edition.slice(1);
      a.click();
    }
  },
};
</script>
<style>
</style>